﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml.XPath;
using HtmlAgilityPack;

namespace 人教课本下载器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void btn浏览下载目录_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txt保存目录.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btn给我下_Click(object sender, EventArgs e)
        {
            if (txt保存目录.Text.Length == 0)
            {
                btn浏览下载目录.PerformClick();
            }

            new Task(() =>
            {
                btn给我下.Enabled = false;
                try
                {
                    // 参考url
                    // http://www.pep.com.cn/gzwl/jszx/tbjx/kb/dzkb/bx1/201107/t20110712_1054707.htm
                    var url = txt扉页地址.Text;
                    var dir = txt保存目录.Text;
                    var pages = Int32.Parse(txt保存页数.Text);

                    var site_root = "http://www.pep.com.cn";
                    var url_root = url.Substring(0, url.LastIndexOf('/') + 1);
                    var url_left = url.Substring(0, url.LastIndexOf('_') + 1);
                    var url_right = url.Substring(url.LastIndexOf('_') + 1);
                    var url_i = Int32.Parse(url_right.Substring(0, url_right.LastIndexOf('.')));

                    process进度.Maximum = pages;
                    for (var i = 0; i < pages; i++)
                    {
                        var html = url_left + (url_i - i).ToString() + ".htm";
                        var client = new HtmlWeb { OverrideEncoding = Encoding.GetEncoding("gb2312") };
                        var doc = client.Load(html);
                        var nodes = doc.DocumentNode.SelectNodes(@"//*[@id=""doccontent""]");
                        if (nodes == null)
                        {
                            if (i == 0)
                                throw new Exception("提供扉页错误，请检查！");
                            continue;
                        }

                        var node = nodes.FindFirst("img");  // 查看源码，此方法不区分大小写
                        if (node == null)
                            continue;

                        foreach (var src in from attr in node.Attributes where attr.Name.ToLower() == "src" select attr)
                        {
                            var src_url = src.Value;
                            // 可能根路径，判断一下
                            var img = ((src_url[0] == '/') ? site_root : url_root) + src_url;
                            if (!Directory.Exists(dir))
                                Directory.CreateDirectory(dir);
                            Web.DownloadFile(img, dir + string.Format(@"\{0:D4}.jpg", i));
                            process进度.Value = i + 1;
                            process进度.Text = "抓取到页面统计：" + process进度.Value.ToString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("未知错误，请查看源码;-)" + ex.Message);
                }
                btn给我下.Enabled = true;
            }).Start();
        }

        static readonly WebClient Web = new WebClient();
    }
}
